package org.example.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * JSON 操作工具类
 * jackson 实现
 */
public class JsonUtils {
    // 创建jackson操作对象，用于object和json之间的相互转换
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * Object转成JSON数据
     */
    public static String toJSONString(Object object) {
        // 基础类型判断
        if(object instanceof Integer || object instanceof Long || object instanceof Float ||
                object instanceof Double || object instanceof Boolean || object instanceof String){
            return String.valueOf(object);
        }
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * JSON数据，转成Object
     */
    public static  <T> T parseObject(String json, Class<T> clazz) {
        try {
            return objectMapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
